<?php
/**
 * Created by PhpStorm.
 * User: Sunmer
 * Date: 2019/6/5 0005
 * Time: 18:44
 * Email:Sunmer@foxmail.com
 */
namespace app\api\controller;

use think\Db;

class Coin extends BaseController{
    /**兑换金币
     * @return \think\Response|\think\response\Json|\think\response\Jsonp|\think\response\Redirect|\think\response\View|\think\response\Xml
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function coin()
    {
        $res = request()->param();
        if (empty($res['id'])||empty($res['coin']))
        {
            return $this->ajax_return('null','参数不完整','201');
        }
        $coin = Db::table('tp_user')->where('id',$res['id'])->find();
        //处理数据
        $coins = $coin['member_coin'] + $res['coin'];
        $diao =  $coin['member_diamonds'] - $res['coin']/2;
        if ($diao>=0)
        {
            $data = [
                'member_coin'=>$coins,
                'member_diamonds'=>$diao,
                'member_ban'=>$diao,
            ];
            $result = Db::table('tp_user')->where('id',$res['id'])->update($data);
            if ($result)
            {
                return $this->ajax_return($data,'兑换成功','200');
            }else{
                return $this->ajax_return([],'兑换失败','201');
            }
        }else{
            return $this->ajax_return('null','您的钻石不足,请充值','201');
        }
    }

    /**
     * 钻石兑换
     * @return \think\Response|\think\response\Json|\think\response\Jsonp|\think\response\Redirect|\think\response\View|\think\response\Xml
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function diam()
    {
        $res = request()->param();
        if (empty($res['id'])||empty($res['diamond']))
        {
            return $this->ajax_return('null','参数不完整','201');
        }
        $coin = Db::table('tp_user')->where('id',$res['id'])->find();
        //处理数据
        $diao = $coin['member_diamonds'] + $res['diamond'];
        $coins=  $coin['member_coin'] - $res['diamond']*2;
        if ($coins>=0){
            $data = [
                'member_coin'=>$coins,
                'member_diamonds'=>$diao,
                'member_ban'=>$diao,
            ];
            $result = Db::table('tp_user')->where('id',$res['id'])->update($data);
            if ($result)
            {
                return $this->ajax_return($data,'兑换成功','200');
            }else{
                return $this->ajax_return([],'兑换失败','201');
            }
        }else{
            return $this->ajax_return('null','您的金币不足','201');
        }
    }
}